package com.ztesoft.report.controller;


import com.ztesoft.report.base.controller.BaseController;
import com.ztesoft.report.base.pojo.R;
import com.ztesoft.report.entity.ReportUserRole;
import com.ztesoft.report.service.ReportUserRoleService;
import com.ztesoft.report.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author y3tu
 * @since 2018-07-25
 */
@RestController
@RequestMapping("/reportUserRole")
public class ReportUserRoleController extends BaseController {
    @Autowired
    UserService UserService;

    @Autowired
    ReportUserRoleService reportUserRoleService;

    /**
     * 获取所有用户和角色
     * @return
     */
    @RequestMapping("/getUserAndRoleList")
    public Object getUserAndRoleList(){
        Map userAndRoleMap = new HashMap<>();
        userAndRoleMap.put("user", UserService.listUsers());
        userAndRoleMap.put("role", UserService.listSysRole());
/*        List<SysUser> users = new ArrayList<>();
        SysUser s = new SysUser();
        s.setUserId("1");
        s.setName("aaaa");
        users.add(s);
        SysUser s1 = new SysUser();
        s1.setUserId("2");
        s1.setName("bbb");
        users.add(s1);
        userAndRoleMap.put("user",users);
        List<SysRoleNew> roles = new ArrayList<>();
        SysRoleNew b = new SysRoleNew();
        b.setRoleId("1");
        b.setRoleName("gggg");
        roles.add(b);
        SysRoleNew b1 = new SysRoleNew();
        b1.setRoleId("2");
        b1.setRoleName("hhhh");
        roles.add(b1);
        userAndRoleMap.put("role",roles);*/
        return userAndRoleMap;
    }

    /**
     * 设置表权限，插表或者更新表
     * @param
     * @return
     */
    @RequestMapping("/setUserAndRole")
    public Object setUserAndRole(@RequestBody ReportUserRole reportUserRole) {
        //原这里使用updateById方法，但是如果userID和roleID为空会出现更新失败，所以使用updateAllColumnById
        //由于前台传回后台的实体reportUserRole并没有创建时间和创建人，所以使用后方法就必须把为空的创建时间和创建人手工加上去
        //并且要在application.yml配置文件里面配置上    jdbc-type-for-null: 'null' ，不然会报错，这是oralce数据库原因
        //springboot 项目mybatis plus 设置 jdbcTypeForNull （oracle数据库需配置JdbcType.NULL, 默认是Other
        String reportId = reportUserRole.getReportId();
        String userIds = reportUserRole.getUserId();
        String roleIds = reportUserRole.getRoleId();
        List<String> userIdList = reportUserRoleService.selectUserIds(reportId);
        List<String> roleIdList = reportUserRoleService.selectRoleIds(reportId);
        //这里我们得到了前台传入的集合 以及 我们库里现存的权限集合，我们对数据进行对比
        // 前台传入而数据库没有的，就是需要新增的
        // 库里现存的而前台没有的，就是我们需要删除的
        //重置公共数据
        reportUserRole.setUserId("");
        reportUserRole.setRoleId("");
        reportUserRole.setCreateUser(getCurrentUser());
        reportUserRole.setUpdateUser(getCurrentUser());
        //如果前台传入的userIds为空的话，下面asList会把空串当作一个值放入集合，所以做个判断
        //开始处理userID
        List<String> newUserList = Arrays.asList(userIds.split(","));
        if (newUserList.size() == 1 && newUserList.get(0) == "") {
            //由于删除元素会报错，所以直接新建
            newUserList = new ArrayList<>();
        }
        Map<String, List> insertAnddelete = listCompareAndHandle(newUserList, userIdList);
        List<String> insertUserList = insertAnddelete.get("insertList");
        List<String> deleteUserList = insertAnddelete.get("deleteList");
        //插入数据库
        if (insertUserList.size() > 0) {
            for (String userId : insertUserList) {
                reportUserRole.setUserId(userId);
                reportUserRole.setRoleId("");
                reportUserRoleService.insert(reportUserRole);
            }
        }
        //删除
        if (deleteUserList.size() > 0) {
            for (String userId : deleteUserList) {
                reportUserRole.setUserId(userId);
                reportUserRole.setRoleId("");
                reportUserRoleService.deleteByUserOrRole(reportUserRole);
            }
        }
        //开始处理roleId
        List<String> newRoleList = Arrays.asList(roleIds.split(","));
        if (newRoleList.size() == 1 && newRoleList.get(0) == "") {
            //由于删除元素会报错，所以直接新建
            newRoleList = new ArrayList<>();
        }
        insertAnddelete = listCompareAndHandle(newRoleList, roleIdList);
        List<String> insertRoleList = insertAnddelete.get("insertList");
        List<String> deleteRoleList = insertAnddelete.get("deleteList");
        //插入数据库
        if (insertRoleList.size() > 0) {
            for (String roleId : insertRoleList) {
                reportUserRole.setUserId("");
                reportUserRole.setRoleId(roleId);
                reportUserRoleService.insert(reportUserRole);
            }
        }
        //删除
        if (deleteRoleList.size() > 0) {
            for (String roleId : deleteRoleList) {
                reportUserRole.setUserId("");
                reportUserRole.setRoleId(roleId);
                reportUserRoleService.deleteByUserOrRole(reportUserRole);
            }
        }
/*        if (userIds != "" && userIds != null) {
            String[] userList = userIds.split(",");
            //reportUserRole实体类是以1,2,3 方式存放了 用户列表和 角色列表，我们要单独用每个角色ID去查询，
            //所以这里查询用户ID自然角色ID是为空的，我们要置为空，下面角色ID同理
            reportUserRole.setRoleId("");
            reportUserRole.setCreateUser(getCurrentUser());
            reportUserRole.setUpdateUser(getCurrentUser());
            for (String userId:userList) {
                reportUserRole.setUserId(userId);
                List<ReportUserRole> oldReportUserRoleList  = reportUserRoleService.selectUserRoleByUserOrRole(reportUserRole);
                if (oldReportUserRoleList != null && oldReportUserRoleList.size() == 0) {
                    //说明用此reportID以及userID查询不到对应数据，所以我们要新增进去
                    reportUserRoleService.insert(reportUserRole);
                }
            }
        }*/
/*        if (roleIds != "" && roleIds != null) {
            String[] roleList = roleIds.split(",");
            reportUserRole.setUserId("");
            reportUserRole.setCreateUser(getCurrentUser());
            reportUserRole.setUpdateUser(getCurrentUser());
            for (String roleId:roleList) {
                reportUserRole.setRoleId(roleId);
                List<ReportUserRole> oldReportUserRoleList  = reportUserRoleService.selectUserRoleByUserOrRole(reportUserRole);
            }
        }*/
        return R.ok();
/*        ReportUserRole oldReportUserRole  = reportUserRoleService.selectById(reportUserRole);
        if (oldReportUserRole != null) {
            reportUserRole.setUpdateUser(getCurrentUser());
            reportUserRole.setUpdateTime(new Date());
            reportUserRole.setCreateTime(oldReportUserRole.getCreateTime());
            reportUserRole.setCreateUser(oldReportUserRole.getCreateUser());
            reportUserRoleService.updateAllColumnById(reportUserRole);
        } else {
            reportUserRole.setUpdateUser(getCurrentUser());
            reportUserRole.setCreateUser(getCurrentUser());
            reportUserRoleService.insert(reportUserRole);
        }
        return R.ok();*/
    }

    /**
     * 此方法用来对比2个权限集合数据，并且增删report_user_role表
     * @param newList 前台传入的新权限集合
     * @param oldList 后台查询的旧权限集合
     */
    public Map listCompareAndHandle(List<String> newList,List<String> oldList) {
        Map insertAnddelete = new HashMap();
        List<String> insertList = new ArrayList<>();
        List<String> deleteList = new ArrayList<>();
        //处理新增数据
        for (String newData:newList) {
            //做个标记，默认为true，当比较中有相同的值则改成true
            boolean flag = true;
            for (String oldData:oldList) {
                if (newData.equals(oldData)) {
                    //说明前台发送的数据库存在，就不用在做处理了
                    flag = false;
                    break;
                }
            }
            if (flag) {
                //说明对比后没发现一样的那么说明这是一条需要新增的数据
                insertList.add(newData);
            }
        }
        //处理删除数据
        for (String oldData:oldList) {
            boolean flag = true;
            for (String newData:newList) {
                if (oldData.equals(newData)) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                deleteList.add(oldData);
            }
        }
        insertAnddelete.put("insertList",insertList);
        insertAnddelete.put("deleteList",deleteList);
        return insertAnddelete;
    }


    /**
     * 获取当前报表的权限列表
     * @param reportUserRole
     * @return
     */
    @RequestMapping("/getReportPermission")
    public Object getReportPermission(@RequestBody ReportUserRole reportUserRole) {
        Map map = new HashMap();
        List userIdList = reportUserRoleService.selectUserIds(reportUserRole.getReportId());
        List roleIdList = reportUserRoleService.selectRoleIds(reportUserRole.getReportId());
        map.put("userIds",userIdList);
        map.put("roleIds",roleIdList);
        return map;
    }


}
